package com.leexuan.ordersystem.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.leexuan.ordersystem.beans.Admin;
import com.leexuan.ordersystem.db.AdminDB;
import com.leexuan.ordersystem.forms.LoginForm;

public class LoginAction extends Action {

	public LoginAction() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		LoginForm lf = (LoginForm) form;
		String username = lf.getUsername();
		String password = lf.getPassword();

		ActionForward forward = new ActionForward();

		Admin admin = new Admin();

		AdminDB db = new AdminDB();

		try {
			db.getConnection();

			boolean isAdmin = db.isAdmin(username, password);

			if (isAdmin) {
				admin = db.getAdminByUsername(username);

				HttpSession session = request.getSession(false);
				if (session != null) {
					session.invalidate();

				}
				session = request.getSession(true);

				session.setAttribute("admin", admin);

				return mapping.findForward("success");
			} else {

				ActionErrors errors = new ActionErrors();
				errors.add("invalidPassword", new ActionMessage("error.login.password.wrong"));
				saveErrors(request, errors);

				return mapping.findForward("failure");
			}

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				db.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
